package com.krain.meijusky.activity;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.util.SparseArrayCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.widget.NestedScrollView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.krain.corelibrary.util.DeviceInfo;
import com.krain.corelibrary.util.ImageLorder;
import com.krain.corelibrary.util.SpUtil;
import com.krain.corelibrary.util.UIUtil;
import com.krain.corelibrary.widget.loadingView.LoadingView;
import com.krain.meijusky.R;
import com.krain.meijusky.constant.SpKeys;
import com.krain.meijusky.entity.ResourceEntity;
import com.krain.corelibrary.util.AnimatorUtil;
import com.krain.meijusky.util.FastBlur;
import com.squareup.picasso.Callback;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * Class description
 *
 * @author yamin
 * @date 2015/11/9 下午 01:57
 */
@EActivity(R.layout.activity_detail)
public class DetailActivity extends BaseActivity {

    @ViewById(R.id.act_detail_collapsing_toolbar)
    CollapsingToolbarLayout ctl_toolbar;
    @ViewById(R.id.act_detail_toolimg)
    ImageView iv_toolImg;
    @ViewById(R.id.act_detail_detailImg)
    ImageView iv_detailImg;
    @ViewById(R.id.act_detail_attrs)
    TextView tv_attrs;
    @Extra("entity")
    ResourceEntity mEntity;
    @ViewById(R.id.act_detail_plot_summary)
    TextView tv_plot_summary;
    @ViewById(R.id.act_detail_download)
    GridLayout gl_download;
    @ViewById(R.id.act_detail_scroolview)
    NestedScrollView mNestedScrollView;
    @ViewById(R.id.loadView)
    LoadingView mLoadingView;
    Document document;
    SparseArrayCompat<String> mUrlMap;

    @Override
    protected String getToolbarTitle() {
        return null;
    }


    @AfterViews
    void afterView() {
        ViewCompat.setTransitionName(iv_detailImg, "img");
        ImageLorder.getInstance(mContext).loadImage(this, iv_toolImg, mEntity.getImg(), callback);
        initCtlToolBar();
        praseHtml();
    }

    void initCtlToolBar() {
        ctl_toolbar.setTitle(mEntity.getTitle());
        ctl_toolbar.setExpandedTitleGravity(Gravity.BOTTOM);
        ctl_toolbar.setExpandedTitleTextAppearance(R.style.MyTextAppearance);
    }


    /**
     * 图片加载结果的回掉
     */
    Callback callback = new Callback() {
        @Override
        public void onSuccess() {
            int value = DeviceInfo.getScreenDisplay(mContext).heightPixels / 4;
            Bitmap bitmap = ((BitmapDrawable) iv_toolImg.getDrawable()).getBitmap();
            float scale = value / (float) bitmap.getHeight();
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams((int) (bitmap.getWidth() * scale), value);
            params.addRule(Gravity.CENTER_VERTICAL);
            params.setMargins(UIUtil.dip2px(mContext, 20), 0, 0, 0);
            iv_detailImg.setLayoutParams(params);
            iv_detailImg.setImageBitmap(bitmap);
            doBlur(bitmap);
        }

        @Override
        public void onError() {

        }
    };


    @Background
    void doBlur(Bitmap bitmap) {
        bitmap = FastBlur.doBlur(bitmap);
        setImage(bitmap);
    }


    @UiThread
    void setImage(Bitmap bitmap) {
        iv_toolImg.setScaleType(ImageView.ScaleType.FIT_XY);
        iv_toolImg.setImageBitmap(bitmap);
        iv_toolImg.setDrawingCacheEnabled(false);
        AnimatorUtil.startRotationY(iv_detailImg, 0, 360, 1700);
    }


    /**
     * 解析详情页的问题
     */
    @Background
    void praseHtml() {
        try {
            String domin = SpUtil.getInstance(mContext).getString(SpKeys.KEY_BASEURI_MEIJUTT, "");
            if (TextUtils.isEmpty(domin)) {
                baseUtil.showSnackBar(mContext, "网址为空");
                hideLoadingView();
                return;
            }
            String detailUrl;
            if (!mEntity.getNextUrl().contains(domin))
                detailUrl = domin.substring(0, domin.length() - 1) + mEntity.getNextUrl();
            else detailUrl = mEntity.getNextUrl();
            document = Jsoup.connect(detailUrl).get();
            Elements elements = document.select("ul[class=omov_list3 font_list3]");
            if (elements != null && elements.size() > 0)
                setPlotSummary(elements);
            setAttrsElements();
            getDownloadUrl();
        } catch (IOException e) {
            e.printStackTrace();
            baseUtil.showSnackBar(mContext, "获取网络数据发生异常");
            hideLoadingView();
        }
    }

    /**
     * 获取美剧属性值
     */
    void setAttrsElements() {
        Elements attrElements = document.select("div[class=o_r_contact]");
        attrElements = attrElements.select("li");
        StringBuffer attrs = new StringBuffer();
        for (Element e : attrElements) {
            String tag = "年份";
            String text = e.text();
            if (text.contains(tag)) {
                String[] arr = text.split(tag);
                attrs.append(arr[0]);
                attrs.append("\n");
                attrs.append(tag + arr[1]);
            } else attrs.append(e.text());
            attrs.append("\n");
        }
        setAttrsText(attrs.toString());
    }


    /**
     * 设置属性值UI
     */
    @UiThread(propagation = UiThread.Propagation.REUSE)
    void setAttrsText(String attsText) {
        tv_attrs.setText(attsText);
    }


    /**
     * 隐藏loadingview
     */
    @UiThread(propagation = UiThread.Propagation.REUSE)
    void hideLoadingView() {
        AnimatorUtil.startCircleReaval(mLoadingView, true);
    }

    /**
     * 获取下载地址的方法
     */
    void getDownloadUrl() {
        Elements downUrl_elements = document.select("ul[class=downurl]");
        if (downUrl_elements.size() == 0 || downUrl_elements == null) {
            baseUtil.showSnackBar(mContext, "暂未获取到下载地址,重试一下");
            hideLoadingView();
            return;
        }
        Element downUrlHd = downUrl_elements.get(downUrl_elements.size() - 1);
        Node downGvod = downUrlHd.childNode(1).childNode(0);
        String[] urlArray = downGvod.attr("data").substring(downGvod.attr("data").indexOf("=") + 3).split("\\u0024down#");
        mUrlMap = new SparseArrayCompat<>();
        int i = 1;
        for (String str : urlArray) {
            mUrlMap.put(i, str.split("\\u0024")[1]);
            i++;
        }
        initGridlayout();
    }


    private final int TAGSPACEPADDING = 15;
    int tagWidth = 0;
    private int widthPixels ;

    /**
     * 给Gridlaout设置数据
     */
    @UiThread(propagation = UiThread.Propagation.REUSE)
    void initGridlayout() {
        widthPixels = UIUtil.getWindowWidth(mContext);
        for (int i = 0; i < mUrlMap.size(); i++) {
            GridLayout.Spec rowSpec = GridLayout.spec(i / gl_download.getColumnCount());
            GridLayout.Spec columnSpec = GridLayout.spec(i % gl_download.getColumnCount());
            GridLayout.LayoutParams params = new GridLayout.LayoutParams(rowSpec, columnSpec);
            params.setMargins(TAGSPACEPADDING, TAGSPACEPADDING, TAGSPACEPADDING, TAGSPACEPADDING);
            ViewGroup viewGroup = (ViewGroup) gl_download.getParent();
            tagWidth = widthPixels - (viewGroup.getPaddingLeft() + viewGroup.getPaddingRight()) - TAGSPACEPADDING * (gl_download.getColumnCount() * 2);
            params.width = tagWidth / gl_download.getColumnCount();
            TextView tagview = new TextView(mContext);
            tagview.setBackgroundResource(R.drawable.selector_episode_button);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
                tagview.setElevation((float) 20);
            tagview.setPadding(20, 20, 20, 20);
            tagview.setGravity(Gravity.CENTER);
            tagview.setTextColor(getResources().getColor(R.color.colorPrimary));
            tagview.setText("第" + (i + 1) + "集");
            gl_download.addView(tagview, params);
            tagview.setOnClickListener(new GridItemClickLisener(i + 1));
        }
        mLoadingView.showContentView(mNestedScrollView);
    }

    @UiThread(propagation = UiThread.Propagation.REUSE)
    void setPlotSummary(Elements elements) {
        tv_plot_summary.setText(elements.text());
    }


    /**
     * 设置gridlayout的点击事件
     */
    class GridItemClickLisener implements View.OnClickListener {
        int position;

        public GridItemClickLisener(int position) {
            this.position = position;
        }

        @Override
        public void onClick(View v) {
            if (!SpUtil.getInstance(getApplicationContext()).getBoolean(SpKeys.KEY_SP_FRIST_DOWNLOAD, false)) {
                //第一次进入APP
                baseUtil.showDialog(mContext, "需要迅雷支持", getString(R.string.download_tips), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SpUtil.getInstance(getApplicationContext()).putBoolean(SpKeys.KEY_SP_FRIST_DOWNLOAD, true);
                        takeThunderAndDownload(position);
                    }
                }, null);
            } else {
                takeThunderAndDownload(position);
            }

        }
    }

    /**
     * 调用迅雷
     *
     * @param position
     */
    void takeThunderAndDownload(int position) {
        //复制下载链接到剪切板
        ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        clipboardManager.setPrimaryClip(ClipData.newPlainText("data", mUrlMap.get(position)));
        Intent intent_test = getPackageManager().getLaunchIntentForPackage("com.xunlei.downloadprovider");
        if (intent_test == null) {
            baseUtil.showSnackBar(mContext, "你没有安装迅雷");
            return;
        }
        openApp();
    }


    private List<Map<String, Object>> list = null;
    private PackageManager mPackageManager;
    private List<ResolveInfo> mAllApps;

    /**
     * 检查系统应用程序，并打开
     */
    private void openApp() {
        //应用过滤条件
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        mPackageManager = mContext.getPackageManager();
        mAllApps = mPackageManager.queryIntentActivities(mainIntent, 0);
        //按报名排序
        Collections.sort(mAllApps, new ResolveInfo.DisplayNameComparator(mPackageManager));

        for (ResolveInfo res : mAllApps) {
            //该应用的包名和主Activity
            String pkg = res.activityInfo.packageName;
            String cls = res.activityInfo.name;

            // 打开QQ
            if (pkg.contains("xunlei")) {
                ComponentName componet = new ComponentName(pkg, cls);
                Intent intent = new Intent();
                intent.setComponent(componet);
                intent.setAction("android.intent.action.MAIN");
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivityForResult(intent, Activity.RESULT_OK);
            }
        }
    }

    public static void jumpTothisActivity(BaseActivity activity, ResourceEntity entity, View view) {
        Intent intent = new Intent(activity, DetailActivity_.class);
        intent.putExtra("entity", entity);
        activity.startAnimActivity(intent, view, "img");
    }
}
